const express = require('express')
const multer = require('multer')
const path = require('path')
const { fileURLToPath } = require('url')
const router = express.Router()
const UUID = require('uuid')
const upload = multer({ dest: '../public/upload/' })
const fileUpload = require('express-fileupload')
    //设置保存规则
    // let storage = multer.diskStorage({
    //     //destination:字段设置上传路径，可以为函数
    //     destination: path.resolve(__dirname + '../public/upload'),
    //     //filename:设置文件保存的文件名
    //     filename: function(req, file, cb) {
    //         let extName = file.originalname.slice(file.originalname.lastIndexOf('.'));
    //         let fileName = UUID.v1()
    //         cb(null, fileName + extName)
    //     }
    // })

// let imageUploader = multer({
//     storage: storage
// }).array('photos', 9)
// let cpUpload = upload.fields({ name: 'file', maxCount: 1 })
// router.post('/', upload.single('photos'), function(req, res, next) {
//     console.log(1)
//     res.send('1')
// })
router.use(fileUpload())
router.post('/', (req, res, next) => {
    console.log(req.files)
    let file = req.files.file;
    let name = req.files.file.name
    file.mv('./public/upload/' + name, function(err) {
        if (err) {
            return console.log(err)
        } else {
            res.send('http://localhost:3000/upload/' + name)

            // res.send('http://49.234.36.18:90/upload/' + name)
        }
    })
});
//上传用户头像
router.post('/avatar', (req, res, next) => {
    console.log(req.files)
    let file = req.files.file;
    let name = req.files.file.name
    file.mv('./public/upload/avatar/' + name, function(err) {
        if (err) {
            return console.log(err)
        } else {
            res.send('http://localhost:3000/upload/avatar/' + name)
                // res.send('http://192.168.43.48:3000/upload/avatar/' + name)
                // res.send('http://49.234.36.18:90/upload/avatar/' + name)
        }
    })
});
//上传商品照片
router.post('/goods', (req, res, next) => {
    console.log(req.body)
    let file = req.files.file;
    let name = req.files.file.name
    file.mv('./public/upload/goods/' + name, function(err) {
        if (err) {
            return console.log(err)
        } else {
            res.send('http://localhost:3000/upload/goods/' + name)
                // res.send('http://49.234.36.18:90/upload/goods/' + name)
        }
    })
});
//上传动态照片
router.post('/square', (req, res, next) => {
    console.log(req.body)
    let file = req.files.file;
    let name = req.files.file.name
    file.mv('./public/upload/square/' + name, function(err) {
        if (err) {
            return console.log(err)
        } else {
            res.send('http://localhost:3000/upload/square/' + name)
                // res.send('http://192.168.43.48:3000/upload/square/' + name)
                // res.send('http://49.234.36.18:90/upload/square/' + name)
        }
    })
})
module.exports = router;